import 'package:common/common.dart';
import 'package:common/http/interceptor/interceptor_cache.dart';
import 'package:get/get.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

import 'pull_refresh_common.dart';

mixin PullRefreshControllerMixin on GetxController {
  final RefreshController refreshController = RefreshController();
  PageStatus pageStatus = PageStatus.loading;
  int page = 1;

  // 结束刷新
  void endrefresh({required bool noData}) {
    refreshController.refreshCompleted();
    noData ? refreshController.loadNoData() : refreshController.loadComplete();
  }

  // 结束加载更多
  void endLoadMore({required bool noData}) {
    noData ? refreshController.loadNoData() : refreshController.loadComplete();
  }

  /// 结束刷新和加载更多
  void pullRefreshEnd() {
    refreshController.loadNoData();
    refreshController.refreshCompleted();
  }

  /// 请求方法
  /// [url] 请求地址
  /// [params] 请求参数
  /// [explain] 接口说明
  /// [modelBuilder] 返回数据模型
  /// [cancelToken] 取消请求
  Future<T?> getRequestModel<T>({
    required String url,
    Map<String, dynamic>? params,
    required String explain, // 接口说明
    required ModelBuilder modelBuilder,
    CancelToken? cancelToken,
  }) async {
    Result result = await HttpProvider.get(url, cancelToken: cancelToken, params: params, explain: explain);
    if (result.succ == true) {
      T model = modelBuilder(result.data) as T;
      pageStatus = PageStatus.success;
      endrefresh(noData: true);
      return model;
    }
    pageStatus = PageStatus.error;
    pullRefreshEnd();
    return null;
  }

  /// 分页请求方法
  /// [url] 请求地址
  /// [params] 请求参数
  /// [explain] 接口说明
  /// [refresh] 是否是刷新请求
  /// [modelBuilder] 返回数据模型
  /// [haveDataBuilder] 是否有数据
  /// [cancelToken] 取消请求
  Future<T?> getRequestList<T>({
    required String url,
    Map<String, dynamic>? params,
    required String explain, // 接口说明
    required ModelBuilder modelBuilder,
    HaveDataBuilder? haveDataBuilder,
    CacheControl? cacheControl, // Get请求是否需要缓存

    bool? refresh,
    CancelToken? cancelToken,
  }) async {
    Result result = await HttpProvider.get(url,
        cancelToken: cancelToken, params: params, explain: explain, cacheControl: cacheControl);
    if (result.succ == true) {
      T model = modelBuilder(result.data) as T;
      if (refresh != null) {
        if (refresh) {
          bool noData = haveDataBuilder?.call(model) ?? true;
          endrefresh(noData: noData);
        } else {
          bool noData = haveDataBuilder?.call(model) ?? true;
          endLoadMore(noData: noData);
        }
      }
      pageStatus = PageStatus.success;
      return model;
    }
    pageStatus = PageStatus.error;
    pullRefreshEnd();
    return null;
  }
}
